﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using WebUI.Controls;

namespace WebUI
{
    public partial class StockTake : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                ReloadData();
                RefreshStockLocation();
                RefreshProductList();
            }
            txtSearchProduct.Focus();
        }

        public void btnLoadByLocation_OnClick(object sender, EventArgs e)
        {
            RefreshStockLocation();
            RefreshProductList();
        }

        public String LocationSessionKey
        {
            get { return ViewState["LocationSessionKey"] != null ? ViewState["LocationSessionKey"].ToString() : ""; }
            set { ViewState["LocationSessionKey"] = value; }
        }

        public StockLocation Locations
        {
            get { return Session[LocationSessionKey] != null ? (StockLocation)Session[LocationSessionKey] : null; }
            set { Session[LocationSessionKey] = value; }
        }

        public String ProductDetailSessionKey
        {
            get { return ViewState["ProductDetailSessionKey"] != null ? ViewState["ProductDetailSessionKey"].ToString() : ""; }
            set { ViewState["ProductDetailSessionKey"] = value; }
        }

        public View_RealProductQuantity ProdDetails
        {
            get { return Session[ProductDetailSessionKey] != null ? (View_RealProductQuantity)Session[ProductDetailSessionKey] : null; }
            set { Session[ProductDetailSessionKey] = value; }
        }

        private void ReloadData()
        {
            Brands brands = Brands.LoadAllActiveBrands();
            Utilities.LoadDropDownList(ddlBrand, brands.DefaultView, Brands.ColumnNames.BrandName, Brands.ColumnNames.ID, "--All--");

            hidSelectedLocation.Value = "-999";
            LocationSessionKey = Guid.NewGuid().ToString();
            Locations = StockLocation.GetAllActiceStockLocation();


            ProductDetailSessionKey = Guid.NewGuid().ToString();
            ProdDetails = View_RealProductQuantity.GetRealQuantity();
            lstProducts.SourceObject = ProdDetails;
        }


        public String GetLocationEditPageLink()
        {
            return "EditPages/EditLocation.aspx?key=" + LocationSessionKey;
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string ProductDetailsKey
        {
            get
            {
                if (ViewState["ProductDetailsKey"] == null)
                    ViewState["ProductDetailsKey"] = Guid.NewGuid().ToString();
                return ViewState["ProductDetailsKey"].ToString();
            }
        }

        protected void btnPrintProduct_OnClick(object sender, EventArgs e)
        {
            ProductListCtrl printedList = (ProductListCtrl)LoadControl(@"~/Controls/POSControls/ProductListCtrl.ascx");
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.SourceObject = ProdDetails;
            printedList.Width = new Unit(100, UnitType.Percentage);
            printedList.GridLineStyle = GridLines.Both;
            printedList.GridBorder = BorderStyle.Solid;
            printedList.GridBorderWidth = new Unit(1, UnitType.Pixel);
            printedList.CssClass = "";
            printedList.Refresh();
            Session[PrintKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);

            lstProducts.Refresh();
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }

        public string GetProductDetailsPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + ProductDetailsKey;
        }

        protected void btnSearchProduct_OnClick(object sender, EventArgs e)
        {
            gridFilterPaging.Reset();
            if (gridFilterPaging.DefaultFilter != "")
                lstProducts.Filter = gridFilterPaging.DefaultFilter + " and (" + Products.ColumnNames.ProductName + " LIKE '%" + txtSearchProduct.Text + "%')";
            else
                lstProducts.Filter = Products.ColumnNames.ProductName + " LIKE '%" + txtSearchProduct.Text + "%'";
            lstProducts.Refresh();
        }

        protected void btnReload_OnClick(object sender, EventArgs e)
        {
            ReloadData();
            RefreshStockLocation();
            lstProducts.Refresh();
        }

        protected void ddlBrand_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            RefreshProductList();
            gridFilterPaging.Reset();
        }

        protected void btnExcel_OnClick(object sender, EventArgs e)
        {
            string filter = ProdDetails.Filter;
            ProdDetails.Filter = "";
            if (SessionUser.Purchase)
                Utilities.ExportToExcel(ProdDetails, "Stock.xls",
                    new String[] { "ProductName", "Cost", "Quantity", "DealerPrice", "SalePrice" },
                    new String[] { "Product", "Cost", "Quantity", "DealerPrice", "SalePrice" },
                    "Stock");
            else
                Utilities.ExportToExcel(ProdDetails, "Stock.xls",
                    new String[] { "ProductName", "Quantity"},
                    new String[] { "Product", "Quantity"},
                    "Stock");
            ProdDetails.Filter = filter;
        }

        private void RefreshStockLocation()
        {
            string oldFilter = Locations.Filter;
            Locations.Filter = StockLocation.ColumnNames.Deleted + "=0";

            Locations.Rewind();
            litLocations.InnerHtml = "";
            for (int i = 0; i < Locations.RowCount; i++)
            {
                string button = String.Format("<input id='{0}' value='{1}' type='button' onclick='btnLocation_click(this)' style='width:100%; margin-top:4px' LocationID='{2}' {3} />",
                    "btn_" + Locations.s_ID, Locations.s_LocationName, Locations.s_ID, Locations.s_ID == hidSelectedLocation.Value ? "class='sortButtonSelected'" : "");

                litLocations.InnerHtml += button;

                Locations.MoveNext();
            }

            litLocations.InnerHtml += "<div style='height:10px'>&nbsp;</div><label class='labelNote'>(*) For non IMEI Products, go to Products Section</label>";

            Locations.Filter = oldFilter;
        }
        
        private void RefreshProductList()
        {
            gridFilterPaging.Reset();

            String id = hidSelectedLocation.Value;
            if (id != "")
                lstProducts.Filter = View_RealProductQuantity.ColumnNames.StockLocationID + " = " + id;

            if (ddlBrand.SelectedIndex > 0)
            {
                if(lstProducts.Filter != "")
                    lstProducts.Filter += " and " + View_RealProductQuantity.ColumnNames.BrandID + "=" + ddlBrand.SelectedValue;
                else
                    lstProducts.Filter = View_RealProductQuantity.ColumnNames.BrandID + "=" + ddlBrand.SelectedValue;
            }

            
            gridFilterPaging.DefaultFilter = lstProducts.Filter;
            lstProducts.Refresh();
            lstProducts.Columns[0].Visible = false;
            lstProducts.Columns[3].Visible = false;
            lstProducts.Columns[4].Visible = false;
            lstProducts.Columns[8].Visible = false;
            lstProducts.Columns[9].Visible = false;

            if (!SessionUser.Purchase)
            {
                lstProducts.Columns[5].Visible = false;
                lstProducts.Columns[10].Visible = false;
            }
        }

        public void btnAddLocation_OnClick(object sender, EventArgs e)
        {
            RefreshStockLocation();
        }

        public void btnViewDetail_OnClick(object sender, EventArgs e)
        {
            if (hidSelectedItemID.Value == "" || hidSelectedLocation.Value == "")
                return;

            View_ProductDetails prod = View_ProductDetails.GetAvailableProductDetailsByProductIDLocationID(int.Parse(hidSelectedItemID.Value), int.Parse(hidSelectedLocation.Value));
            ProductDetailListCtrl printedList = (ProductDetailListCtrl)LoadControl(@"~/Controls/POSControls/ProductDetailListCtrl.ascx");
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.SourceObject = prod;
            printedList.Width = new Unit(100, UnitType.Percentage);
            printedList.GridLineStyle = GridLines.Both;
            printedList.GridBorder = BorderStyle.Solid;
            printedList.GridBorderWidth = new Unit(1, UnitType.Pixel);
            printedList.CssClass = "";
            printedList.Refresh();

            Session[ProductDetailsKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetProductDetailsPage()), true);

            lstProducts.Refresh();
        }

        public void gridFilterPaging_OnNeedListControl(Object sender, EventArgs e)
        {
            gridFilterPaging.ListControl = lstProducts;
        }

        public void btnRemoveLocation_OnClick(object sender, EventArgs e)
        {
            if (hidSelectedLocation.Value == "")
                return;
            if (!ProductDetails.IsStockEmpty(int.Parse(hidSelectedLocation.Value)))
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("alert('Can only delete empty stock. All products in stock must be transfered before it is deleted!')", 1), true);
                return;
            }

            string oldFilter = Locations.Filter;
            Locations.Filter = StockLocation.ColumnNames.ID + "=" + hidSelectedLocation.Value;
            if (Locations.RowCount > 0)
            {
                Locations.Deleted = true;
                //Locations.LastModifiedByUser = 
                Locations.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                Locations.Save();
                Locations.Filter = oldFilter;
                RefreshStockLocation();
            }
            else
                Locations.Filter = oldFilter;
        }
    }
}
